<?php

namespace app\admin\model;

use ba\Exception;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Log;
use think\Model;

/**
 * Export
 */
class Export extends Model
{
    // 表名
    protected $name = 'export';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;


    public function getExportFilePathAttr($val){
        return $val ? full_url($val) : '';
    }

    /**
     * 导出会员卡密码
     *
     * @param \app\admin\model\Export $export 导出记录
     * @return bool
     */
    public function exportCode($export)
    {
        // 解析查询参数
        $query_params = json_decode($export->query_params, true);
        [
            'where'         => $where,
            'alias'         => $alias,
            'order'         => $order,
            'withJoinTable' => $withJoinTable,
            'withJoinType'  => $withJoinType,
        ] = $query_params;

        // 获取数据
        $list = (new \app\admin\model\vip\Code())
            ->withJoin($withJoinTable, $withJoinType)
            ->where($where)
            ->select()
            ->toArray();

        if (empty($list)) {
            Log::warning("导出任务ID[{$export->id}]没有匹配的数据");
        }

        // 创建表格
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue([1, 1], 'ID');
        $sheet->setCellValue([2, 1], '用户名');
        $sheet->setCellValue([3, 1], '会员卡');
        $sheet->setCellValue([4, 1], '卡号');
        $sheet->setCellValue([5, 1], '卡密');
        $sheet->setCellValue([6, 1], '状态');
        $sheet->setCellValue([7, 1], '最后使用时间');
        $sheet->setCellValue([8, 1], '创建时间');

        // 设置列宽
        $columns = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
        foreach ($columns as $column) {
            $sheet->getColumnDimension($column)->setWidth(20);
        }

        // 填充数据
        $row = 2;
        foreach ($list as $v) {
            $status_text = $v['status'] == 0 ? "未使用" : '已使用';
            $sheet->setCellValue([1, $row], $v['id']);
            $sheet->setCellValue([2, $row], $v['admin']['nickname'] ?? '');
            $sheet->setCellValue([3, $row], $v['vipCard']['name'] ?? '');
            $sheet->setCellValue([4, $row], $v['number']);
            $sheet->setCellValue([5, $row], $v['password']);
            $sheet->setCellValue([6, $row], $status_text);
            $sheet->setCellValue([7, $row], date('Y-m-d H:i:s', $v['user_expire_time'] ?? 0));
            $sheet->setCellValue([8, $row], date('Y-m-d H:i:s', $v['create_time'] ?? 0));
            $sheet->getStyle('C' . $row)->getAlignment()->setWrapText(true);
            $row++;
        }

        try {
            $writer = new Xlsx($spreadsheet);

            // 设置导出目录
            $exportDir = public_path() . 'export/';

            // 检查目录是否存在，不存在则创建
            if (!is_dir($exportDir)) {
                mkdir($exportDir, 0755, true);
            }

            // 完整的文件路径
            $file = $exportDir . $export['name'];

            // 保存文件
            $writer->save($file);

            // 更新导出文件的路径信息
            $export->export_file_path = '/export/' . $export['name'];
            $export->status = 2; // 成功状态
            $export->export_finish_time = time(); // 成功状态
            $export->save();

            Log::info("导出任务ID[{$export->id}]完成");

            return true;
        } catch (\Exception $e) {
            Log::error("导出文件保存失败: " . $e->getMessage());
            throw new Exception("导出文件保存失败: " . $e->getMessage());
        }
    }

}
